var express = require('express');
var router = express.Router();
var fs = require('fs');
var connection = require('../mysql/mysql');

var oss = require('ali-oss');
// var oss = require('multer-oss');
var multer = require('multer');
let upload = multer({dest: 'uploads/'});

var client = new oss({
  accessKeyId: 'LTAI4G2sa8vJGM5Rd5vojEZQ',
  accessKeySecret: 'FKtUG9ZdSllQW1KGMTkNTsranAf1BP',
  bucket: 'xxudong',
  region: 'oss-cn-hangzhou'
});

//文件上传
router.post('/upload', upload.single("file"), function (req, res, next) {
  let data = req.body;
  let file = req.file;
  var localFile = './' + file.path;

  //判断文件是否存在
  client.get(`${data.directory}/${file.originalname}`).then((result) => {
    if (result.res.status == 200) {
      // 上传之后删除本地文件
      fs.unlinkSync(localFile);
      return res.json({
        code: 0,
        data: result.res.requestUrls[0],
        success: true,
        message: '上传成功！',
      });
    }
  }).catch((e)=> {
    if (e.code == 'NoSuchKey') {
      put();
    }else {
      fs.unlinkSync(localFile);
      return res.json({
        code: 1,
        data: e,
        success: true,
        message: '上传失败！',
      });
    }
  });

  async function put() {
    try {
      let result = await client.put(`${data.directory}/${file.originalname}`, localFile, {headers: {'x-oss-forbid-overwrite': true}});
      // 上传之后删除本地文件
      fs.unlinkSync(localFile);
      return res.json({
        code: 0,
        data: result.url,
        success: true,
        message: '上传成功！',
      });
    } catch (err) {
      // 上传之后删除本地文件
      fs.unlinkSync(localFile);
      return res.json({
        code: 1,
        data: err,
        success: true,
        message: '上传失败！',
      });
    }
  }

});

//删除文件
router.post('/removeFile', function (req, res, next) {
  let url = req.body.url;
  let object = url.replace("http://xxudong.oss-cn-hangzhou.aliyuncs.com/","");
  async function deleteFile() {
    try {
      let result = await client.delete(object);
      return res.json({
        code: 0,
        data: null,
        success: true,
        message: '删除成功！',
      });
    } catch (err) {
      return res.json({
        code: 1,
        data: err,
        success: true,
        message: '删除失败！',
      });
    }
  }

  deleteFile();
});

module.exports = router;
